'use strict';

// Login
angular.module('simon.controllers').controller('LoginCtrl', ['$scope', 'LoginFactory', 'AlertFactory', '$location', '$rootScope', '$route', '$cookieStore', 
  function ($scope, LoginFactory, AlertFactory, $location, $rootScope, $route, $cookieStore) {
	$rootScope.usuarioLogado = $cookieStore.get('usuarioLogado');
	
	$rootScope.$on("$routeChangeSuccess", function(current) {
		var authRequired = $route.current && $route.current.$$route && $route.current.$$route.auth;
        if (authRequired && !$rootScope.usuarioLogado) {
        	AlertFactory.add("danger", "Login necessario para acessar esta pagina!");
            $location.url(".");
        } 
    });
	
	/* callback for ng-click 'login': */
    $scope.login = function () {
    	$scope.loginForm.$setPristine();
    	$scope.item = LoginFactory.show({ login: $scope.item.login, senha: $scope.item.senha }, 
    		function (success) { 
    			if ($scope.item.id == null) {
    				AlertFactory.add("danger", "Falha ao autenticar, verifique os dados informados!");
    				setLoginInfo(null);
    			} else {
    				setLoginInfo($scope.item);
        			$location.url(".");
    			}
    		},
    		function (error) { 
    			AlertFactory.add("danger", "Falha ao autenticar, verifique os dados informados!"); 
    			setLoginInfo(null);
    		}
    	);
    };
    
    /* callback for ng-click 'logout': */
    $scope.logout = function () {
    	$scope.item = null;
    	setLoginInfo(null);
    };
    
    function setLoginInfo(usuarioLogado) {
    	$cookieStore.put('usuarioLogado', usuarioLogado);
		$rootScope.usuarioLogado = usuarioLogado;
    };
  }]);
